"""
基线矫正模块
"""

import numpy as np


class BaselineCorrector:
    """基线矫正器类"""
    
    def msc_correction(self, data: np.ndarray) -> np.ndarray:
        """
        多元散射校正 (MSC)
        
        Args:
            data: 输入光谱数据
            
        Returns:
            np.ndarray: MSC矫正后的数据
        """
        # 计算平均光谱作为参考
        mean_spectrum = np.mean(data, axis=0)
        
        # 对每个样本进行MSC校正
        corrected_data = np.zeros_like(data)
        for i in range(data.shape[0]):
            # 线性回归：spectrum = a * mean_spectrum + b
            A = np.vstack([mean_spectrum, np.ones(len(mean_spectrum))]).T
            coeffs, _, _, _ = np.linalg.lstsq(A, data[i], rcond=None)
            a, b = coeffs
            
            # MSC校正：(spectrum - b) / a
            if abs(a) > 1e-10:  # 避免除零
                corrected_data[i] = (data[i] - b) / a
            else:
                corrected_data[i] = data[i]
        
        return corrected_data
    
    def snv_correction(self, data: np.ndarray) -> np.ndarray:
        """
        标准正态变量变换 (SNV)
        
        Args:
            data: 输入光谱数据
            
        Returns:
            np.ndarray: SNV矫正后的数据
        """
        # 对每个样本进行SNV校正
        corrected_data = np.zeros_like(data)
        for i in range(data.shape[0]):
            mean_val = np.mean(data[i])
            std_val = np.std(data[i])
            
            # SNV校正：(spectrum - mean) / std
            if std_val > 1e-10:  # 避免除零
                corrected_data[i] = (data[i] - mean_val) / std_val
            else:
                corrected_data[i] = data[i] - mean_val
        
        return corrected_data
    
    def no_correction(self, data: np.ndarray) -> np.ndarray:
        """
        不进行基线矫正（返回原始数据）
        
        Args:
            data: 输入光谱数据
            
        Returns:
            np.ndarray: 原始数据
        """
        return data.copy()